<template>
    <div style="width: 960px;height: 400px;margin-top: 20px">
        <div style="width: 960px;height: 40px">
            <a-row>
                <a-col :span="6">
                    <a-select defaultValue="请选择设备" style="width: 160px;margin-left: 20px" @change="handleChange" >

<!--                        <a-select-opt-group v-for="c in clientdata" :key="c">-->
                            <a-select-option v-for="c in clientdata" :key="c" :value="c">{{c}}</a-select-option>
<!--                        </a-select-opt-group>-->

                    </a-select>
                </a-col>

                <a-col :span="10" style="z-index: 999">
                    <div style="z-index: 999">
                        <div style="width: 80px;float: left">
                            <a-input placeholder="数据名" v-model="name"/>
                        </div>
                        <div style="width: 80px;float: left;margin-left: 10px">
                            <a-input placeholder="数据源名" v-model="dataname"/>
                        </div>
                        <div style="float: left;margin:10px;z-index:999">
                            <colorPicker v-model="color" />
                        </div>
                        <a-button @click="addTag">添加</a-button>
                        <a-button @click="addChart" style="margin-left: 10px">获取数据</a-button>
                    </div>
                </a-col>
                <a-col :span="8">
                    <div v-for="(item,i) in tagsdata" :key="i" style="margin: 5px; float: left">
                        <a-tag :color="item.color" closable @close="log(i)">{{item.name}}</a-tag>
                    </div>
                </a-col>
            </a-row>

        </div>
        <div style="background-color: #fff;margin: 5pt;border-radius: 4pt;z-index: 1" >
            <v-chart ref="dom" id="chart" :options="line" style="width: 100%;height: 200pt" v-if="chart"/>
            <a-empty v-if="!chart" style="margin-top: 100px"
                     image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original">
                <span slot="description"> 暂无数据 </span>
            </a-empty>
        </div>




    </div>

</template>

<script>
    import ECharts from 'vue-echarts'
    import 'echarts/lib/chart/line'
    import 'echarts/lib/component/polar'
    import echarts from 'echarts'
    import {getlastdata, getdata, getClient} from "@/api/mqtt";
    export default {
        name: "DevChart",
        components: {
            'v-chart': ECharts
        },
        data(){
            return{
                //scale,
                chart:false,
                tagsdata:[],
                clientdata:[],
                clientid:'',
                name:'',
                dataname:'',
                color: '#ff0000',
                timer:'',
                symbolSize :20,
                dom:null,
                line :{title: {
                        text: '变化曲线图'
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            label: {
                                backgroundColor: '#666'
                            }
                        }
                    },
                    legend: {
                        data: ['温度', '湿度']
                    },
                    toolbox: {
                        feature: {
                            saveAsImage: {}
                        }
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: [
                        {
                            type: 'category',
                            boundaryGap: false,
                            data: [],
                        }
                    ],
                    yAxis:[{
                        type:'value',
                    }],
                    dataZoom: [
                        {
                            type: "slider",
                            realtime: true, //拖动滚动条时是否动态的更新图表数据
                            height: 20, //滚动条高度
                            start: 80, //滚动条开始位置（共100等份）
                            end: 100 //结束位置（共100等份）
                        }
                    ],
                    series: [
                        {
                            name: '温度',
                            type: 'line',
                            //   stack: '总量',
                            smooth:true,
                            symbol:'none',
                            areaStyle: {
                                normal : {
                                    color:'#f5ca72',   // 设置最高气温线的颜色
                                }
                            },

                            data: [],
                            itemStyle : {
                                normal : {
                                    color:'#f5ca72',   // 设置最高气温线的颜色
                                }
                            },
                        },
                        {
                            name: '湿度',
                            type: 'line',

                            smooth:true,
                            symbol:'none',
                            areaStyle: {

                                normal : {
                                    color:'#9cd6f5',   // 设置最高气温线的颜色
                                }
                            },

                            data: [],
                            itemStyle : {
                                normal : {
                                    color:'#9cd6f5',   // 设置最高气温线的颜色
                                }
                            },
                        },

                    ]},





            }
        },created(){



        },
        mounted() {
            //this.timer = setInterval(this.getLastdata, 10000);
            //this.getData()
            this.getClients()
        },
        beforeDestroy() {
            clearInterval(this.timer);
        }, methods: {
            getClients(){
                //console.log("4-挂载，实例被创建时执行")
                getClient().then((res)=>{
                   // console.log(res.data)
                    this.data=res.data
                    res.data.forEach((item)=>{
                        //console.log(item.clientid)
                            this.clientdata.push(item.clientid)
                       // console.log(this.clientdata)

                    })
                }).catch()
            },
            addChart(){
                clearInterval(this.timer);
                this.line.series[0].data=[]
                this.line.series[1].data=[]
                this.line.xAxis[0].data=[]
                this.tagsdata.forEach((data,i)=>{
                    this.line.series[i+2].data=[]//item["payload"][data.dataname])
                })
                this.getData()
                this.timer = setInterval(this.getLastdata, 10000);

            },
            log(e) {
               // console.log(e);
                this.tagsdata.splice(e,1)
                this.line.legend.data.splice(e+2,1)
               // console.log(this.tagsdata)
            },
            addTag(){
                this.tagsdata.push({"name":this.name,"color":this.color,"dataname":this.dataname})
                this.line.legend.data.push(this.name)
                this.line.series.push({
                    name: this.name,
                    type: 'line',

                    smooth:true,
                    symbol:'none',
                    areaStyle: {

                        normal : {
                            color:this.color,   // 设置最高气温线的颜色
                        }
                    },

                    data: [],
                    itemStyle : {
                        normal : {
                            color:this.color,   // 设置最高气温线的颜色
                        }
                    },
                })
                this.drewLine()
            },
            headleChangeColor(){
                //console.log(this.color)
            },

            handleChange(value) {
                //console.log(`selected ${value}`);
                this.clientid=value
            },

            drewLine(){
                var chart=echarts.init(document.getElementById("chart"))
                //this.line={}
                chart.clear();
                chart.setOptions(this.line)

            },

            getData(){

                getdata(this.clientid).then((reponse)=>{
                        const result=reponse.data;
                        this.chart=(reponse.data.length==0 ? false: true)
                        result.forEach((item)=>{
                            this.line.series[0].data.unshift(item["payload"]["temp"])
                            this.line.series[1].data.unshift(item["payload"]["hum"])
                            this.line.xAxis[0].data.unshift(item["add_time"])
                            this.tagsdata.forEach((data,i)=>{
                                this.line.series[i+2].data.unshift(item["payload"][data.dataname])
                            })
                        })
                        this.drewLine()

                    }

                ).catch(

                )
            },
            getLastdata(){
                getlastdata(this.clientid).then((response)=>{
                    const  result=response.data
                    result.forEach((item)=>{
                       // console.log(item["payload"])
                         const data=JSON.parse(item["payload"])
                        //console.log(data.hum)
                        this.line.series[1].data.push(data.hum)
                        this.line.series[0].data.push(data.temp)
                        this.line.xAxis[0].data.push(item["add_time"])
                        this.tagsdata.forEach((data,i)=>{
                            this.line.series[i+2].data.unshift(item["payload"][data.dataname])
                        })


                    })

                }).catch()
            }

        },
    }
</script>

<style scoped>
    .echarts {
        width: 100%;
        height: 100%;
    }
</style>
